package com.qk.interceptor;

import com.qk.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
//@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求路径
        String uri = request.getRequestURI();  //  /login  /users
        //判断是否为登录请求,如果是,放行
        if (uri.contains("login")){
            log.info("登录请求");
            return  true;
        }
        //获取请求头中的token
        String jwt = request.getHeader("token");
        //判断token是否存在,如果不存在,响应401
        if (jwt == null || jwt.isEmpty()){
            log.info("token不存在");
            response.setStatus(401);
            return false;
        }
        //解析令牌,如果解析令牌报错,响应401
        try {
            JwtUtils.parseToken(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //放行
        log.info("令牌合法,放行");
        return  true;
    }
}

